package com.pichub.psdmaster;

import com.pichub.psdmaster.filesDao.FileInfoDao;
import com.pichub.psdmaster.filesDao.impl.FileInfoDaoImpl;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import psd.Layer;
import psd.Psd;
import psd.parser.layer.LayerType;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * 大致思路
 * 1.先检查psd的md5是否唯一
 * 2.检查输出的图层psd是否唯一
 * 如果唯一 正常保存上传
 * 如果不唯一 将id关联起来（需要创建一个中间表-多对多）
 * Created by davis on 2016/6/26.
 */

public class testcreatepng {

    public static Pattern p = Pattern.compile("[\\u005C/:\\u002A\\u003F\"<>\'\\u007C’‘“”：？\t\r\n]");
    public static FileInfoDao fidao = new FileInfoDaoImpl();
    private static final String basePath="H:\\psdparars";

    public static void main(String[] args) {

        long starttime = System.currentTimeMillis();

        try {

            File fileDir = new File(basePath+"\\test");

            File[] filearray = fileDir.listFiles();

            for (int i = 0; i < filearray.length; i++) {

                File file = filearray[i];

                FileInputStream fis = new FileInputStream(file);

                String md5 = DigestUtils.md5Hex(IOUtils.toByteArray(fis));

                //这里需要检查md5值是否在数据库中有记录
                if (null != fidao.findIdByMD5(md5)) {
                    continue;
                }

                IOUtils.closeQuietly(fis);

                String filename = file.getName().substring(0, file.getName().lastIndexOf("."));

                String newpathdir = basePath+"\\parserresult" + File.separator + md5 + File.separator;

                Psd psdFile = new Psd(file);

                BufferedImage bi = psdFile.getBaseLayer().getImage();

                // 保存预览图

                savePic(bi, newpathdir + filename + ".png",filename + ".png","preview");

                // 循环保存各个图层

                List<Layer> layers = psdFile.getLayers();

                extractImage(newpathdir, layers);

                System.err.println("完成-->" + psdFile.getName());

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

        long endtime = System.currentTimeMillis();

        System.out.println("共计花掉时间:" + (endtime - starttime));


    }


    private static void extractImage(String newpathdir, List<Layer> layers) {

        for (Layer layer : layers) {

            String name = "";

            name = clearSpecilChar(layer.getName());

            if (layer.getType() == LayerType.HIDDEN) {

                if (StringUtils.isBlank(name)) {
                    name = System.currentTimeMillis() + ".png";
                } else {
                    name = name + ".png";
                }

                System.out.println(name);

                if (null != layer.getImage()) {

                    savePic(layer.getImage(), newpathdir + name,name,"layer");

                }

            } else if (layer.getType() == LayerType.FOLDER) {

                System.out.println("FOLDER:" + layer.getName());

                if (layer.getLayersCount() > 0) {
                    extractImage(newpathdir, layer.getLayers());
                }

            } else {
                if (StringUtils.isBlank(name)) {
                    name = System.currentTimeMillis() + ".png";
                } else {
                    name = name + ".png";
                }
                if (null != layer.getImage()) {
                    savePic(layer.getImage(), newpathdir + name,name,"layer");
                }

            }

        }

    }


    public static void savePic(BufferedImage bi, String pathAndName,String name,String pictype) {

        // 首先创建一个BufferedImage变量，因为ImageIO写图片用到了BufferedImage变量。

        // 再创建一个Graphics变量，用来画出来要保持的图片，及上面传递过来的Image变量

        try {
            // 将BufferedImage变量写入文件中。
            makeDirs(pathAndName);
            File saveFile = new File(pathAndName);

            if (saveFile.exists()) {
                saveFile = new File(pathAndName.substring(0, pathAndName.lastIndexOf(".")) + System.currentTimeMillis() + ".png");
            }

            ImageIO.write(bi, "png", saveFile);
            String ossObjPath="";
            if("preview".equals(pictype)){
                ossObjPath="pichub/previewpic/";
            }else if("layer".equals(pictype)){
                ossObjPath="pichub/layer/";
            }else if("src".equals(pictype)){
                ossObjPath="pichub/psdsrc/";
            }else {
                ossObjPath="pichub/others/";
            }
            com.pichub.psdmaster.PostObjectSample ossPostObject = new com.pichub.psdmaster.PostObjectSample(saveFile.getAbsolutePath(),name,ossObjPath);
            ossPostObject.PostObject();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static boolean makeDirs(String filePath) {

        String folderName = getFolderName(filePath);

        if (folderName == null || folderName.isEmpty()) {

            return false;

        }


        File folder = new File(folderName);

        return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();

    }


    public static String getFolderName(String filePatn) {

        if (null != filePatn) {

            return filePatn.substring(0, filePatn.lastIndexOf(File.separator));

        }

        return null;

    }


    /**
     * 过滤文件中的特殊字符
     *
     * @param name
     * @return
     */

    public static String clearSpecilChar(String name) {

        Matcher m = p.matcher(name);

        return m.replaceAll("-").trim();

    }


}